package com.cbtx.networklib.util

import android.util.Log
import java.io.File
import java.io.FileInputStream
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/2 3:07 PM
 * desc   :
 */
object MD5Util {
    private val TAG = "MD5Util"

    /**
     * 默认的密码字符串组合，用来将字节转换成 16 进制表示的字符
     */
    var sMessageDigest: MessageDigest? = null

    init {
        try {
            sMessageDigest = MessageDigest.getInstance("MD5")
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
    }


    fun getStringMD5(str: String): String {
        val buffer = str.toByteArray()
        sMessageDigest!!.update(buffer)
        return byteToHex(sMessageDigest!!.digest())
    }


    fun getFileMD5(file: File): String? {
        var md5: String? = ""
        if (file.exists() && file.isFile) {
            try {
                FileInputStream(file).use { `in` ->
                    val md = MessageDigest.getInstance("MD5")
                    val buffer = ByteArray(1024)
                    var read: Int
                    while (`in`.read(buffer).also { read = it } != -1) {
                        md.update(buffer, 0, read)
                    }
                    val data = md.digest()
                    md5 = byteToHex(data)
                }
            } catch (e: Exception) {
                Log.d(TAG, e.message!!)
            }
        }
        return md5
    }


    private fun byteToHex(bytes: ByteArray): String {
        val hexDigits = charArrayOf(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'
        )
        val stringbuffer = StringBuffer(2 * bytes.size)
        for (b in bytes) {
            val c0 = hexDigits[b.toInt() ushr 4 and 0xf]
            val c1 = hexDigits[b.toInt() and 0xf]
            stringbuffer.append(c0)
            stringbuffer.append(c1)
        }
        return stringbuffer.toString()
    }
}